<?php

namespace Iaem\HomeBundle\Services;

use Doctrine\ORM\EntityManager;
use Iaem\HomeBundle\Entity\Vote;
use Iaem\UserBundle\Entity\User;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 */
class Voter {

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    /**
     * @var \Symfony\Component\HttpFoundation\Session\Session
     */
    protected $session;

    /**
     * @param Session $session
     * @param EntityManager $entityManager
     */
    public function __construct(Session $session, EntityManager $entityManager)
    {
        $this->em      = $entityManager;
        $this->session = $session;
    }

    public function canVote(User $user)
    {
        return !$this->isVotedLast24Hours($user);
    }

    public function vote(User $user)
    {
        if (!$this->isVotedLast24Hours($user)) {
            $vote = new Vote();
            $user->setLastVotedTime(new \DateTime());
            $vote->setUser($user);

            $this->em->persist($vote);
            $this->em->flush();

            return true;
        } else {
            return false;
        }
    }

    public function isVotedLast24Hours(User $user)
    {
        if ($user->getLastVotedTime() && $user->getLastVotedTime()->getTimestamp() > 0) {
           if ((new \DateTime())->getTimestamp() - $user->getLastVotedTime()->getTimestamp() <= 86400) {
                return true;
           } else {
               return false;
           }
        }

        return false;
    }

}
